package com.xyhuo.leetcode.january;

import java.util.ArrayList;
import java.util.List;

/**
 * 最大交换
 * https://leetcode.cn/problems/maximum-swap/
 *
 * @time 2024/1/22
 */
public class MaximumSwap {

//    public static void main(String[] args) {
//        MaximumSwap ms = new MaximumSwap();
//        int i = ms.maximumSwap(98368);
//        System.out.println(i);
//    }

    public int maximumSwap(int num) {
        int tmpNum = num;
        List<Integer> list = new ArrayList<>();
        while (true) {
            if (tmpNum > 9) {
                list.add(tmpNum % 10);
                tmpNum /= 10;
            } else {
                list.add(tmpNum);
                break;
            }
        }
        for (int i = list.size() - 1; i >= 0; i--) {
            int max = list.get(i);
            int maxIndex = i;
            for (int j = i - 1; j >= 0; j--) {
                if (list.get(j) >= max) {
                    max = list.get(j);
                    maxIndex = j;
                }
            }
            if (list.get(i) != max) {
                int tmp = max;
                list.set(maxIndex, list.get(i));
                list.set(i, tmp);
                return toNum(list);
            }
        }
        return num;
    }

    private Integer toNum(List<Integer> nums) {
        int ans = 0;
        for (int i = 0; i < nums.size(); i++) {
            ans += Math.pow(10, i) * nums.get(i);
        }
        return ans;
    }
}
